/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on 22-Jun-2011, 8:18:47 PM
 */
package desktopapplication;

import java.awt.Dimension;
import java.awt.Insets;
import pack.Course;
import java.io.IOException;
import java.awt.geom.RoundRectangle2D;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import static desktopapplication.FunctionLibrary.*;
import static desktopapplication.GlobalVariables.*;

/**
 *
 * @author 王舒嶷
 */
public class MainFrame extends javax.swing.JFrame implements ActionListener {

    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();
        timer.start();
        com.sun.awt.AWTUtilities.setWindowShape(this, new RoundRectangle2D.Double(0, 0, this.getWidth(), this.getHeight(), 8D, 8D));
        //com.sun.awt.AWTUtilities.setWindowOpacity(this, 0.93f);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jOptionPane1 = new javax.swing.JOptionPane();
        LogInPanel = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        PasswordField = new javax.swing.JPasswordField();
        UsernameField = new javax.swing.JTextField();
        LoadingPanel = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        CourseSelectPanel = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        addLabel = new javax.swing.JLabel();
        editLabel = new javax.swing.JLabel();
        removeLabel = new javax.swing.JLabel();
        CourseEditPanel = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        QuestionPanel = new javax.swing.JPanel();
        quicklyAddQuestionType = new javax.swing.JComboBox();
        quicklyAddQuestionTitle = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        createAndStartButton = new javax.swing.JButton();
        createAndSaveButton = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        countTextFiled = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();

        jOptionPane1.setMessage("Incorrected username or password !");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setAlwaysOnTop(true);
        setResizable(false);
        setUndecorated(true);
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                formMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                formMouseReleased(evt);
            }
        });
        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                formMouseDragged(evt);
            }
        });
        getContentPane().setLayout(null);

        LogInPanel.setBackground(java.awt.SystemColor.activeCaption);
        LogInPanel.setPreferredSize(new java.awt.Dimension(250, 400));

        jLabel2.setText("Password:");

        jLabel1.setText("Username:");

        jButton1.setText("Log In");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel3.setText("Our logo here");

        PasswordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                PasswordFieldKeyReleased(evt);
            }
        });

        UsernameField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                UsernameFieldKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout LogInPanelLayout = new javax.swing.GroupLayout(LogInPanel);
        LogInPanel.setLayout(LogInPanelLayout);
        LogInPanelLayout.setHorizontalGroup(
            LogInPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(LogInPanelLayout.createSequentialGroup()
                .addGroup(LogInPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(LogInPanelLayout.createSequentialGroup()
                        .addGap(87, 87, 87)
                        .addComponent(jButton1))
                    .addGroup(LogInPanelLayout.createSequentialGroup()
                        .addGap(46, 46, 46)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(67, Short.MAX_VALUE))
            .addGroup(LogInPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(LogInPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(LogInPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2))
                    .addGap(35, 35, 35)
                    .addGroup(LogInPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(UsernameField)
                        .addComponent(PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(36, Short.MAX_VALUE)))
        );
        LogInPanelLayout.setVerticalGroup(
            LogInPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, LogInPanelLayout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 197, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(59, 59, 59))
            .addGroup(LogInPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(LogInPanelLayout.createSequentialGroup()
                    .addGap(178, 178, 178)
                    .addGroup(LogInPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(UsernameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(LogInPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(164, Short.MAX_VALUE)))
        );

        getContentPane().add(LogInPanel);
        LogInPanel.setBounds(0, 15, 250, 400);
        /*LogInPanel.setBounds(this.getInsets().left,
            15 + this.getInsets().top,
            LogInPanel.getPreferredSize().width,
            LogInPanel.getPreferredSize().height);*/

        LoadingPanel.setBackground(java.awt.SystemColor.activeCaption);

        jLabel5.setText("Loading Page");

        javax.swing.GroupLayout LoadingPanelLayout = new javax.swing.GroupLayout(LoadingPanel);
        LoadingPanel.setLayout(LoadingPanelLayout);
        LoadingPanelLayout.setHorizontalGroup(
            LoadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(LoadingPanelLayout.createSequentialGroup()
                .addGap(92, 92, 92)
                .addComponent(jLabel5)
                .addContainerGap(94, Short.MAX_VALUE))
        );
        LoadingPanelLayout.setVerticalGroup(
            LoadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(LoadingPanelLayout.createSequentialGroup()
                .addGap(167, 167, 167)
                .addComponent(jLabel5)
                .addContainerGap(219, Short.MAX_VALUE))
        );

        getContentPane().add(LoadingPanel);
        LoadingPanel.setBounds(0, 15, 250, 400);
        LoadingPanel.setVisible(false);

        CourseSelectPanel.setBackground(java.awt.SystemColor.activeCaption);
        CourseSelectPanel.setPreferredSize(new java.awt.Dimension(250, 400));

        jLabel4.setText("Choose a course:");

        jButton2.setText("Next");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jList1.setFont(new java.awt.Font("Berlin Sans FB Demi", 0, 18));
        jList1.setModel(courseListModel);
        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jList1.setDoubleBuffered(true);
        jScrollPane1.setViewportView(jList1);

        addLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
        addLabel.setForeground(new java.awt.Color(0, 0, 255));
        addLabel.setText("Add...");
        addLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                addLabelMouseClicked(evt);
            }
        });

        editLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
        editLabel.setForeground(new java.awt.Color(0, 0, 255));
        editLabel.setText("Edit...");
        editLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                editLabelMouseClicked(evt);
            }
        });

        removeLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
        removeLabel.setForeground(new java.awt.Color(0, 0, 255));
        removeLabel.setText("Remove...");
        removeLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                removeLabelMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout CourseSelectPanelLayout = new javax.swing.GroupLayout(CourseSelectPanel);
        CourseSelectPanel.setLayout(CourseSelectPanelLayout);
        CourseSelectPanelLayout.setHorizontalGroup(
            CourseSelectPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(CourseSelectPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(CourseSelectPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(CourseSelectPanelLayout.createSequentialGroup()
                        .addGroup(CourseSelectPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                            .addComponent(addLabel)
                            .addComponent(removeLabel))
                        .addContainerGap())
                    .addGroup(CourseSelectPanelLayout.createSequentialGroup()
                        .addComponent(editLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 117, Short.MAX_VALUE)
                        .addComponent(jButton2)
                        .addGap(38, 38, 38))))
        );
        CourseSelectPanelLayout.setVerticalGroup(
            CourseSelectPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(CourseSelectPanelLayout.createSequentialGroup()
                .addGap(83, 83, 83)
                .addComponent(jLabel4)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(CourseSelectPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(CourseSelectPanelLayout.createSequentialGroup()
                        .addComponent(addLabel)
                        .addGap(18, 18, 18)
                        .addComponent(editLabel))
                    .addComponent(jButton2))
                .addGap(18, 18, 18)
                .addComponent(removeLabel)
                .addGap(44, 44, 44))
        );

        getContentPane().add(CourseSelectPanel);
        CourseSelectPanel.setBounds(0, 15, 250, 400);
        CourseSelectPanel.setVisible(false);

        CourseEditPanel.setBackground(java.awt.SystemColor.activeCaption);
        CourseEditPanel.setPreferredSize(new java.awt.Dimension(250, 400));

        jLabel6.setText("courseEditPanel");

        javax.swing.GroupLayout CourseEditPanelLayout = new javax.swing.GroupLayout(CourseEditPanel);
        CourseEditPanel.setLayout(CourseEditPanelLayout);
        CourseEditPanelLayout.setHorizontalGroup(
            CourseEditPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(CourseEditPanelLayout.createSequentialGroup()
                .addGap(81, 81, 81)
                .addComponent(jLabel6)
                .addContainerGap(93, Short.MAX_VALUE))
        );
        CourseEditPanelLayout.setVerticalGroup(
            CourseEditPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(CourseEditPanelLayout.createSequentialGroup()
                .addGap(174, 174, 174)
                .addComponent(jLabel6)
                .addContainerGap(212, Short.MAX_VALUE))
        );

        getContentPane().add(CourseEditPanel);
        CourseEditPanel.setBounds(0, 15, 250, 400);
        CourseEditPanel.setVisible(false);

        QuestionPanel.setBackground(java.awt.SystemColor.activeCaption);
        QuestionPanel.setPreferredSize(new java.awt.Dimension(250, 400));

        quicklyAddQuestionType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Multiple Choice: 6 Options" }));

        quicklyAddQuestionTitle.setText("NewQuestion");

        jLabel7.setText("Title:");

        jLabel9.setText("Question Type:");

        jLabel8.setText("Quickly Create and Start a Question");

        createAndStartButton.setText("Creat & Start Voting");

        createAndSaveButton.setText("Create & Save");
        createAndSaveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createAndSaveButtonActionPerformed(evt);
            }
        });

        jLabel10.setText("Count:");

        countTextFiled.setText("120");

        jLabel11.setText("s");

        javax.swing.GroupLayout QuestionPanelLayout = new javax.swing.GroupLayout(QuestionPanel);
        QuestionPanel.setLayout(QuestionPanelLayout);
        QuestionPanelLayout.setHorizontalGroup(
            QuestionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(QuestionPanelLayout.createSequentialGroup()
                .addGroup(QuestionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(QuestionPanelLayout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(jLabel8))
                    .addGroup(QuestionPanelLayout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(jLabel7))
                    .addGroup(QuestionPanelLayout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(quicklyAddQuestionTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(QuestionPanelLayout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(countTextFiled, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(QuestionPanelLayout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(jLabel9))
                    .addGroup(QuestionPanelLayout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(quicklyAddQuestionType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(QuestionPanelLayout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(createAndSaveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(QuestionPanelLayout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(createAndStartButton, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(46, 46, 46))
        );
        QuestionPanelLayout.setVerticalGroup(
            QuestionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(QuestionPanelLayout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jLabel8)
                .addGap(32, 32, 32)
                .addComponent(jLabel7)
                .addGap(6, 6, 6)
                .addComponent(quicklyAddQuestionTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30)
                .addGroup(QuestionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(countTextFiled, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11))
                .addGap(31, 31, 31)
                .addComponent(jLabel9)
                .addGap(18, 18, 18)
                .addComponent(quicklyAddQuestionType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(42, 42, 42)
                .addComponent(createAndSaveButton)
                .addGap(11, 11, 11)
                .addComponent(createAndStartButton))
        );

        getContentPane().add(QuestionPanel);
        QuestionPanel.setBounds(0, 15, 250, 400);
        QuestionPanel.setVisible(false);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-250)/2, (screenSize.height-415)/2, 250, 415);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        LoadingPanel.setVisible(true);
        LogInPanel.setVisible(false);
        LoginRunnable r = new LoginRunnable(UsernameField.getText(), PasswordField.getPassword(), this);
        Thread t = new Thread(r);
        t.start();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        goToQuestionPage(this);
    }//GEN-LAST:event_jButton2ActionPerformed
    private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed
        // TODO add your handling code here:
        isDraging = true;
        xx = evt.getX();
        yy = evt.getY();
    }//GEN-LAST:event_formMousePressed

    private void formMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseReleased
        // TODO add your handling code here:
        isDraging = false;
    }//GEN-LAST:event_formMouseReleased

    private void formMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseDragged
        if (isDraging) {
            int left = this.getLocation().x;
            int top = this.getLocation().y;
            this.setLocation(left + evt.getX() - xx, top + evt.getY()
                    - yy);
            //this.repaint();//the difference with or without??
        }
    }//GEN-LAST:event_formMouseDragged

    private void addLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addLabelMouseClicked
        createCourseButtonClicked(this);
    }//GEN-LAST:event_addLabelMouseClicked

    private void removeLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeLabelMouseClicked
        // TODO add your handling code here:
        removeCourseButtonClicked(this);
    }//GEN-LAST:event_removeLabelMouseClicked

    private void editLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_editLabelMouseClicked
        // TODO add your handling code here:
        editCourseButtonClicked(this);
    }//GEN-LAST:event_editLabelMouseClicked

    private void createAndSaveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createAndSaveButtonActionPerformed
        // TODO add your handling code here:
        createAndSaveQuestion(this);
    }//GEN-LAST:event_createAndSaveButtonActionPerformed

    private void PasswordFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_PasswordFieldKeyReleased
        // TODO add your handling code here:
        if (evt.getKeyCode() == 10) {// Enter is released
            LoadingPanel.setVisible(true);
            LogInPanel.setVisible(false);
            LoginRunnable r = new LoginRunnable(UsernameField.getText(), PasswordField.getPassword(), this);
            Thread t = new Thread(r);
            t.start();
        }
    }//GEN-LAST:event_PasswordFieldKeyReleased

    private void UsernameFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_UsernameFieldKeyReleased
        // TODO add your handling code here:
        if (evt.getKeyCode() == 10) {// Enter is released
            LoadingPanel.setVisible(true);
            LogInPanel.setVisible(false);
            LoginRunnable r = new LoginRunnable(UsernameField.getText(), PasswordField.getPassword(), this);
            Thread t = new Thread(r);
            t.start();
        }
    }//GEN-LAST:event_UsernameFieldKeyReleased
    @Override
    public void actionPerformed(ActionEvent e) {
        if (isDraging || !this.isVisible()) {
            return;
        }
        left = this.getLocationOnScreen().x;
        top = this.getLocationOnScreen().y;
        width = this.getWidth();
        height = this.getHeight();
        screenXX = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
        right = screenXX - left - width;
        //System.out.println(isDraging);

        // 获取窗体的轮廓
        rect = new Rectangle(0, 0, width, height);
        // 获取鼠标在窗体的位置
        point = this.getMousePosition();
        if (left < 0 && isPtInRect(rect, point)) {
            this.setLocation(0, top); // 隐藏在左边，鼠标指到后显示窗体；
        } else if (left > -5 && left < 5 && !(isPtInRect(rect, point))) {
            this.setLocation(left - width + 5, top); // 窗体移到左边便边缘隐藏到左边；
        } else if ((top < 0 && left < 0) && isPtInRect(rect, point)) {//窗体在左上角；
            this.setLocation(0, 0);// 窗口隐藏了，鼠标指到他，就显示出来；
        } else if ((top > -5 && top < 5) && (left > -5 && left < 5)
                && !(isPtInRect(rect, point))) {
            // 当窗体的上边框与屏幕的顶端的距离小于5时 ，
            // 并且鼠标不再窗体上将窗体隐藏到屏幕的顶端
            this.setLocation(left - width + 1, 5);
        } else if ((top < 0) && isPtInRect(rect, point)) {
            this.setLocation(left, 0);// 窗口隐藏了，鼠标指到他，就显示出来；
        } else if (top > -5 && top < 5 && !(isPtInRect(rect, point))) {
            // 当窗体的上边框与屏幕的顶端的距离小于5时 ，
            // 并且鼠标不再窗体上将窗体隐藏到屏幕的顶端
            this.setLocation(left, 5 - height);
        } else if (right < 0 && isPtInRect(rect, point)) {
            this.setLocation(screenXX - width + 1, top);// 隐藏在右边，鼠标指到后显示；
        } else if (right > -5 && right < 5 && !(isPtInRect(rect, point))) {
            this.setLocation(screenXX - 5, top); // 窗体移到屏幕右边边缘隐藏到右边；
        } else if (right < 0 && top < 0 && isPtInRect(rect, point)) {//窗体在右上角；
            this.setLocation(screenXX - width + 1, 0);// 隐藏在右边，鼠标指到后显示；
        } else if ((right > -5 && right < 5) && (top > -5 && top < 5)
                && !(isPtInRect(rect, point))) {
            this.setLocation(screenXX - 5, 1); // 窗体移到屏幕右边边缘隐藏到右边；
        }

    }

    public boolean isPtInRect(Rectangle rect, Point point) {
        if (rect != null && point != null) {
            int x0 = rect.x;
            int y0 = rect.y;
            int x1 = rect.width;
            int y1 = rect.height;
            int x = point.x;
            int y = point.y;
            return x >= x0 && x < x1 && y >= y0 && y < y1;
        }
        return false;
    }

    //Accessors and Muators here
    public javax.swing.JPanel getCourseSelectPanel() {
        return CourseSelectPanel;
    }

    public javax.swing.JPanel getLoadingPanel() {
        return LoadingPanel;
    }

    public javax.swing.JPanel getQuestionPanel() {
        return QuestionPanel;
    }

    public javax.swing.JPanel getLogInPanel() {
        return LogInPanel;
    }

    public javax.swing.JOptionPane getjOptionPane1() {
        return jOptionPane1;
    }

    public javax.swing.JList getCourseSelectList() {
        return this.jList1;
    }
    
    public javax.swing.JTextField getQuicklyAddQuestionTitle(){
        return this.quicklyAddQuestionTitle;
    }
    // end
    /**
     * @param args the command line arguments
     */
    private Rectangle rect;
    // 窗体离屏幕左边的距离
    private int left;
    // 窗体离屏幕右边的距离；
    private int right;
    // 屏幕的宽度；
    private int screenXX;
    // 窗体离屏幕顶部的距离
    private int top;
    // 窗体的宽
    private int width;
    // 窗体的高
    private int height;
    // 鼠标在窗体的位置
    private Point point;
    private Timer timer = new Timer(10, this);
    private int xx, yy;
    private boolean isDraging = false;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel CourseEditPanel;
    public javax.swing.JPanel CourseSelectPanel;
    public javax.swing.JPanel LoadingPanel;
    public javax.swing.JPanel LogInPanel;
    private javax.swing.JPasswordField PasswordField;
    private javax.swing.JPanel QuestionPanel;
    private javax.swing.JTextField UsernameField;
    private javax.swing.JLabel addLabel;
    private javax.swing.JTextField countTextFiled;
    private javax.swing.JButton createAndSaveButton;
    private javax.swing.JButton createAndStartButton;
    private javax.swing.JLabel editLabel;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JList jList1;
    private javax.swing.JOptionPane jOptionPane1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField quicklyAddQuestionTitle;
    private javax.swing.JComboBox quicklyAddQuestionType;
    private javax.swing.JLabel removeLabel;
    // End of variables declaration//GEN-END:variables
}

/**
 * A thread which will be called when user click login
 * @author 王舒嶷
 */
class LoginRunnable implements Runnable {

    public LoginRunnable(String username, char[] password, MainFrame frame) {
        this.username = username;
        this.password = password;
        this.frame = frame;
    }

    public void run() {
        try {
            Thread.sleep(1000);
        } catch (Exception ex) {
        }
        String password_ = "";
        for (char e : password) {
            password_ += e;
        }
//        System.out.println("0");
        try {
            sendCommandLogin(username, password_);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
//        System.out.println("1");
//        while(!in.hasNextBoolean()){
//            
//        }
        boolean success = false;
        try {
            success = in.readBoolean();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        if (success) {
            try {
                UserProfile.user_id = in.readInt();
                UserProfile.firstName = (String) in.readObject();
                UserProfile.lastName = (String) in.readObject();
                UserProfile.username = (String) in.readObject();
                frame.getCourseSelectPanel().setVisible(true);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            //get the course list and display it on the Jlist
            try {
                courseList = sendCommandGetCourseList(UserProfile.user_id);
            } catch (IOException ex) {
                Logger.getLogger(ShowCourseListManagementRunnable.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(ShowCourseListManagementRunnable.class.getName()).log(Level.SEVERE, null, ex);
            }
            courseListModel.clear();
            for (Course e : courseList) {
                courseListModel.addElement(e.getTitle());
            }
            frame.getCourseSelectList().ensureIndexIsVisible(courseListModel.size() - 1);
            Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(courseList.size() + "\n");
//            SwingUtilities.invokeLater(new Runnable() {
//
//                public void run() {
//                    frame.getCourseSelectList().ensureIndexIsVisible(courseListModel.size() - 1);
//                }
//            });
        } else {
            frame.getLogInPanel().setVisible(true);
            JOptionPane.showMessageDialog(frame, "Uncorrect username or password !", "Error", JOptionPane.INFORMATION_MESSAGE);

        }
        frame.getLoadingPanel().setVisible(false);
    }
    private String username;
    private char[] password;
    private MainFrame frame;
}

/**
 * A thread which will be called when user want to change panel to courseManagementPanel
 * @author 王舒嶷
 */
class ShowCourseListManagementRunnable implements Runnable {

    public ShowCourseListManagementRunnable(MainFrame frame) {
        this.frame = frame;
    }

    @Override
    public void run() {
        frame.getLogInPanel().setVisible(false);
        frame.getCourseSelectPanel().setVisible(true);
        try {
            courseList = sendCommandGetCourseList(UserProfile.user_id);
        } catch (IOException ex) {
            Logger.getLogger(ShowCourseListManagementRunnable.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ShowCourseListManagementRunnable.class.getName()).log(Level.SEVERE, null, ex);
        }
        courseListModel.clear();
        for (Course e : courseList) {
            courseListModel.addElement(e.getTitle());
        }
        Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(courseList.size() + "\n");
        
        frame.getCourseSelectList().ensureIndexIsVisible(courseListModel.size() - 1);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                frame.getCourseSelectList().ensureIndexIsVisible(courseListModel.size() - 1);
            }
        });
    }
    private MainFrame frame;
}